package com.qdxwx.manage.controller.order;

import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.coupon.CouponCodeService;
import com.qdxwx.data.service.order.OrderAllotDetailService;
import com.qdxwx.data.service.order.OrderDetailService;
import com.qdxwx.data.service.order.OrderService;
import com.qdxwx.data.service.user.UserLetterService;
import com.qdxwx.data.service.user.UserService;
import com.qdxwx.manage.controller.BaseController;

import com.qdxwx.manage.support.SessionUtils;
import com.qdxwx.models.coupon.CouponCode;
import com.qdxwx.models.enums.LetterTemplate;
import com.qdxwx.models.enums.OrderStatus;
import com.qdxwx.models.enums.OrderType;
import com.qdxwx.models.manager.Manager;
import com.qdxwx.models.order.Order;
import com.qdxwx.models.order.OrderAllotDetail;
import com.qdxwx.models.order.OrderDetail;
import com.qdxwx.models.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 课程订单Controller
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Controller
@RequestMapping("/order")
public class OrderInfoController extends BaseController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private CouponCodeService couponCodeService;
    @Autowired
    private UserLetterService userLetterService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderAllotDetailService orderAllotDetailService;

    /**
     * 到订单详情页面
     */
    @RequestMapping("/view.html")
    public String orderInfo(HttpServletRequest request, ModelMap mmap) {
        String orderNo = request.getParameter("orderNo");
        if (TKString.isEmpty(orderNo)) {
            return error404;
        }
        Order order = orderService.getByOrderNo(orderNo);
        if (order == null) {
            return error404;
        }
        User user = userService.get(order.getUserId());
        if (user == null) {
            return error404;
        }
        CouponCode couponCodeDTO = couponCodeService.get(order.getCouponCodeId());
        if (couponCodeDTO == null) {
            couponCodeDTO = new CouponCode();
        }
        List<OrderDetail> orderDetails = orderDetailService.getListByOrderId(order.getOrderId());
        List<OrderAllotDetail> orderAllotDetails = new ArrayList<>();
        if(order.getOrderType().equals(OrderType.COURSE.toString()) && order.getStatus().equals(OrderStatus.SUCCESS.toString())){
            orderAllotDetails.addAll(orderAllotDetailService.getListByOrderNo(order.getOrderNo()));
        }
        mmap.put("user", user);
        mmap.put("order", order);
        mmap.put("orderDetails", orderDetails);
        mmap.put("orderAllotDetails", orderAllotDetails);
        mmap.put("couponCodeDTO", couponCodeDTO);
        return "order/order-info";
    }

    /**
     * 关闭课程：更改状态为closed
     */
    @PostMapping("/close.json")
    @ResponseBody
    public AjaxResult close(HttpServletRequest request) {
        Manager manager = SessionUtils.getManager();
        if (manager == null) {
            return error("登录超时");
        }
        long id = TKConvert.toLong(request.getParameter("id"));
        if (id < 1) return error("参数异常");
        OrderDetail orderDetail = orderDetailService.get(id);
        if (orderDetail == null) {
            return error("找不到指定数据");
        }
        String str = "后台关闭，执行人" +
                manager.getManagerName() +
                "(id:" +
                manager.getManagerId() +
                ")";
        orderDetail.setAuthStatus(OrderStatus.CLOSED.toString());
        orderDetail.setDescription(str);
        orderDetail.setUpdateTime(LocalDateTime.now());
        int row = orderDetailService.update(orderDetail);
        if (row > 0) {
            Order order = orderService.get(orderDetail.getOrderId());
            order.setStatus(OrderStatus.CLOSED.toString());
            orderService.updateOrder(order);
            userLetterService.send(orderDetail.getUserId(), LetterTemplate.ORDER_CLOSE, orderDetail.getCourseName());
        }
        return toAjax(row);
    }


    /**
     * 订单延期:只有订单状态为SUCCESS 才可以进行延期操作
     */
    @RequestMapping("/delay.json")
    @ResponseBody
    public AjaxResult delayOrder(HttpServletRequest request) {
        long id = TKConvert.toLong(request.getParameter("id"));
        if (id < 1) return error("缺少id参数");
        LocalDate authDate = TKConvert.toLocalDate(request.getParameter("authDate"));
        OrderDetail orderDetailUpd = orderDetailService.get(id);
        if (orderDetailUpd == null) return error("找不到指定数据");
        if (!orderDetailUpd.getAuthStatus().equals("SUCCESS")) return error("该订单未付款,不能延期");
        if (orderDetailUpd.getAuthDate().isAfter(authDate)) {
            return error("延期时间必须大于原来的到期时间");
        }
        orderDetailUpd.setAuthDate(authDate);
        orderDetailUpd.setUpdateTime(LocalDateTime.now());
        orderDetailUpd.setDescription("订单延期");
        int row = orderDetailService.update(orderDetailUpd);
        if (row > 0) {
            userLetterService.send(orderDetailUpd.getUserId(), LetterTemplate.ORDER_DELAY, orderDetailUpd.getCourseName());
        }
        return toAjax(row);
    }

}
